$(function(){
	$('.cfmOrder_heard img').bind('click',function(){
		window.location.href = document.referrer; //返回上一页并刷新
	});
	var obj = {
		goodId : 0,						//商品id
		adressId : 0,					//收货地址ID
		skuId: null,					//skuid
		name : $('.Name'),				//姓名
		tel : $('.telephone'),			//联系方式
		Province : $('.province'),		//省
		City : $('.city'),				//市
		Area : $('.area'),				//区
		goodName : $('.goodName'),		//商品名称
		goodAttr : $('.goodAttr'),		//已选商品属性
		goodPrice : $('.goodPrice'),	//商品价格
		goodNum : $('.goodNum'),		//商品数量
		botNum : $('.botNum'),			//底部的数量
		botMoney : $('.botMoney'),		//底部的总金额
		payMoney : $('.payMoney'),		//支付窗口的价格
		num : $('.num.float'),			//商品加减处的数量
		pic : $('.smallPic'),			//缩略图
		skuPoint:0,						//纯集分商品支付
		formHoutai: $('.formHoutai'),	//账户集分
		formCount: $('.formCount'),		//需要集分
		botPoint: $('.bot_point'),		//底部结算总集分
		infoPoint: $('.info_point'),	//信息框的集分
		surePoint: $('.sure_point')		//支付方式框的总集分
	}
	
	loadPage();     //进入页面加载地址
	function loadPage(){
		showGoodInfo();		//进入页面立即执行，加载商品信息
		if(localStorage.getItem('data')){	//如果有编辑地址也的缓存地址加载缓存地址，首次进入页面加载地址页的默认地址
			var adressData = JSON.parse(localStorage.getItem('data'));
			obj.name.text(adressData.name);
			obj.tel.text(adressData.tel);
			obj.Province.text(adressData.sheng);
			obj.City.text(adressData.shi);
			obj.Area.text(adressData.qu);
			obj.adressId = adressData.id;
			confirmPay();	//如果地址存在才可以使用下单功能
		}else{
			promptlyLoad();
			confirmPay();	//如果地址存在才可以使用下单功能
		}
	}
	
	//加载地址信息
	function promptlyLoad(){
		$.ajax({
			type:"post",
			url:"http://a.91jfk.com/Product/Address/address_default",
			dataType:'json',
			success:function(res){
				console.log(res);
				if(res.code == '1'){
					var data = res.msg;
					obj.adressId = data.id;
					obj.name.text(data.name);
					obj.tel.text(data.tel);
					obj.Province.text(data.area);
					obj.City.text(data.street);
					obj.Area.text(data.address);
				} else {
					$(".errAlert").text("请添加地址...").addClass("AlertShow");
					setTimeout(function() {
						$(".errAlert").removeClass("AlertShow");
					}, 3000);
				}
			},
			error:function(err){
				console.log(err)
			}
		});
	}
	
	function showGoodInfo(){
		obj.goodId = localStorage.getItem('jfdhid');
		obj.skuId = localStorage.getItem('skuId');
		obj.goodName.text(localStorage.getItem('jfdhname'));
		obj.goodPrice.text(localStorage.getItem('jfdhprice'));
		obj.goodNum.text(localStorage.getItem('jfdhnum'));
		obj.num.val(localStorage.getItem('jfdhnum'));
		obj.goodAttr.text(localStorage.getItem('jfdhyixuan').replace(/'/g,''));
		obj.pic[0].src = localStorage.getItem('jfdhpic');
		obj.botNum.text(localStorage.getItem('jfdhnum'));
		obj.skuPoint = localStorage.getItem('skuPoint');
		obj.infoPoint.text(localStorage.getItem('skuPoint'));
		//计算总金额和总集分
		var total = ((localStorage.getItem('jfdhnum')) * (localStorage.getItem('jfdhprice'))).toFixed(2);
		obj.botMoney.text(total);
		var TotalPoint = (obj.num.val() * localStorage.getItem('skuPoint'));
		obj.botPoint.text(TotalPoint);
		obj.formCount.text(TotalPoint);
	}
	
	//商品数量加减
    //数量加按钮  
    $(".buy_num .add").click(function(){  
        obj.num.val(parseInt(obj.num.val()) + 1);
        obj.botNum.text(parseInt(obj.botNum.text()) + 1);
        obj.goodNum.text(parseInt(obj.goodNum.text()) + 1);
        $(".buy_num .reduce").removeAttr("disabled");           //当按加1时，设置$(".buy_num .reduce")为可点击状态
        //计算总现金和总集分
        var countTotal = (obj.goodNum.text() * (localStorage.getItem('jfdhprice'))).toFixed(2);
        var totalPoint = (obj.goodNum.text() * (localStorage.getItem('skuPoint')));
        obj.botMoney.text(countTotal);
    	obj.botPoint.text(totalPoint);
    	obj.formCount.text(totalPoint);
    });
    //数量减按钮  
    $(".buy_num .reduce").click(function(){  
        if (parseInt(obj.num.val()) > 1) {                 		 	//判断数量值大于1时才可以减少  
        	obj.num.val(parseInt(obj.num.val()) - 1);
        	obj.botNum.text(parseInt(obj.botNum.text()) - 1);
        	obj.goodNum.text(parseInt(obj.goodNum.text()) - 1);
        	//计算总金额和总集分
    		var countTotal = (obj.goodNum.text() * (localStorage.getItem('jfdhprice'))).toFixed(2);
    		var totalPoint = (obj.goodNum.text() * (localStorage.getItem('skuPoint')));
    		obj.botMoney.text(countTotal);
    		obj.botPoint.text(totalPoint);
    		obj.formCount.text(totalPoint);
        }else{  
        	$(".buy_num .reduce").attr("disabled",true);  		//当num为1时，设置$(".buy_num .reduce")为不可点击状态
        	$(".errAlert").text("商品数量至少为一件").addClass("AlertShow");
        	setTimeout(function(){
	        	$(".errAlert").removeClass("AlertShow");
	        },3000);  
       	} 
    });
    
	//点击顶部跳转地址页面
	$('.address').bind('click',function(){
		window.location.href = 'jfdhguanlidizhi.html';
	});
	
    //点击滑动开关
    $('.switch').bind('click',function(){
    	if($('.switch').is(':checked')){
    		console.log('我是滑动开关，我被点击了...');
	 	}
    });
    
    //点击确认下单按钮
    function confirmPay(){
		var amount = $('.num.float').val();		//商品数量
		console.log('商品id：'+obj.goodId,'商品skuid：'+obj.skuId,'地址id：'+obj.adressId);
    	$('.cfmOrder_cfm').bind('click',function(){
    		console.log(localStorage.getItem('jfdhprice'));
    		$.ajax({
				type:"post",
				url:"http://a.91jfk.com/Product/Nowbuy/create_order",
				data:{
					id:obj.goodId,
					sku_combination:obj.skuId,
					num:amount,
					address_id:obj.adressId
				},
				dataType:'json',
				success:function(res){
					console.log(res);
					if (res.code == 1) {
						obj.formHoutai.text(res.point_num);
						console.log(res.point_num,localStorage.getItem('skuPoint'));
						if(localStorage.getItem('jfdhprice') == '0.00'){	//纯集分支付
				    		if ((res.point_num - 0) >= (localStorage.getItem('skuPoint') - 0)) {
				    			$('.mask').css('display','block');
					    		$('.cfmOrder_foot').css('display','none');
					    		$('.pointPay').show().find('.point_sure').click("click",function(){	
						    		$.ajax({
						    			url:"http://a.91jfk.com/Product/Nowbuy/des_num",
						    			type:"post",
						    			data:{
						    				orderid:res.orderid
						    			},
						    			dataType:'json',
						    			success:function(res){
						    				console.log(res);
						    				$(".errAlert").text(res.message).addClass("AlertShow");
									    	setTimeout(function(){
									        	$(".errAlert").removeClass("AlertShow");
									        },3000);
									        $('.mask').hide();
									        $('.pointPay').hide();
						    			},
						    			error:function(err){
						    				console.log(err);
						    			}
						    		});
					    		});
				    		} else{
				    			$(".errAlert").text("您的积分余额不足...").addClass("AlertShow");
						    	setTimeout(function(){
						        	$(".errAlert").removeClass("AlertShow");
						        },3000);
				    		}
				    	}else{	//集分加现金支付
				    		$('.cfmOrder_foot').css('display','none');
					    	$('.payment_foot').css('display','block');
					    	$('.mask').css('display','block');
					    	var payMoney = (amount * localStorage.getItem('jfdhprice')).toFixed(2);
					    	var payTotalPoint = (amount * localStorage.getItem('skuPoint'));
					    	obj.payMoney.text(payMoney);
					    	obj.surePoint.text(payTotalPoint);
					    	if (payMoney == obj.botMoney.text()) {
								//点击圆圈选择支付方式
							    var payWay;		//用于记录支付方式
							    $('.mode_row').bind('click',function(){
							    	$(this).children('.row_Rt').find('.pur').addClass('addCir');
							    	$(this).siblings().children('.row_Rt').find('.pur').removeClass('addCir');
							    	var a = $(this).children('input[type=hidden]').val();
							    	//payWay = $(this).children('.row_con').find('.mode_name').text();
							    	payWay = a;
							    	console.log(payWay,obj.goodId,amount,obj.adressId,obj.skuId);
							    	//点击确认支付
							    	$('.confirm_cfm').unbind('click').click(function(){
								    	if(payWay == '1'){
											console.log('微信支付');
											console.log(res.orderid);
											$.ajax({
												url: "http://a.91jfk.com/Product/WxJsAPI/jsApiCall",
												type: "post",
												data: {
													orderId: res.orderid
												},
												datatype: "json",
												success: function(xhr) {
													console.log(xhr);
													var data = JSON.parse(xhr);
													callpay(data.jsApiParameters);
												},
												error: function(err) {
													console.log(err);
													console.log('支付失败');
												}
											});//ajax结束
										}else if(payWay == '2'){
											console.log('连连支付');
											//location.href = "../Lianlianpay/send/no_order/" + order; //连连接口
										}else{
											console.log('请选择付款方式...');
											$(".errAlert").text("请选择付款方式...").addClass("AlertShow");
									    	setTimeout(function(){
									        	$(".errAlert").removeClass("AlertShow");
									        },3000);
										}
								    });
							    });
					    	}
				    	}
					}else{
						$(".errAlert").text(res.message).addClass("AlertShow");
			        	setTimeout(function(){
				        	$(".errAlert").removeClass("AlertShow");
				        },3000);
					}
				},
				error:function(err){
					console.log(err);
				}
			});
	    });
    }
    
    //纯集分支付、取消支付
    $('.point_cancel').click(function(){
    	$('.mask').hide();
		$('.cfmOrder_foot').show();
		$('.pointPay').hide();
    });
    
    //调用微信支付接口
    function callpay(arg) {
		if(typeof WeixinJSBridge == "undefined") {
			if(document.addEventListener) {
				document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
			} else if(document.attachEvent) {
				document.attachEvent('WeixinJSBridgeReady', jsApiCall);
				document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
			}
		} else {
			jsApiCall(arg);
		}
	}

	//调用微信JS api 支付
	function jsApiCall(arg) {
		var data = JSON.parse(arg);
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',
			data,
			function(res) {
				WeixinJSBridge.log(res.err_msg);
				if(res.err_msg == "get_brand_wcpay_request:ok") {
					//alert("支付成功");
				} else if(res.err_msg == "get_brand_wcpay_request:cancel") {
					//alert("取消支付");
				} else {
					//alert(res.err_msg);
					//alert("支付失败");
				}
			});
	}
    
    //点击关闭按钮
    $('.close').bind('click',function(){
    	$('.cfmOrder_foot').css('display','block');
    	$('.payment_foot').css('display','none');
    	$('.mask').css('display','none');
    });
});
